import store from '@/store'
import { toast, jump } from '@/common/util'

function getCurrentUrl() {
  const routes = getCurrentPages() // 获取当前打开过的页面路由数组
  const curRoute = routes[routes.length - 1].route // 获取当前页面路由
  const paramsMap = routes[routes.length - 1].options // 获取路由参数
  // 拼接参数
  let params = ''
  for (const key in paramsMap) {
    params += '&' + key + '=' + paramsMap[key]
  }
  if (params) {
    return curRoute + '?' + params
  } else {
    return curRoute
  }
}

export function redirectLogin() {
  const currentUrl = getCurrentUrl()
  store.commit('user/setHistory', currentUrl)
  jump('/passport/login/login')
}

export function redirectLoginSuccess() {
  const redirectUrl = store.getters.history
  const menus = store.getters.menu
  if (menus.length === 0) {
    toast('账号无权限')
  } else {
    if (redirectUrl) {
      if (redirectUrl.startsWith('pages/order/order') ||
        redirectUrl.startsWith('pages/statistics/statistics') ||
        redirectUrl.startsWith('pages/car/car') ||
        redirectUrl.startsWith('pages/driver/driver') ||
        redirectUrl.startsWith('pages/mine/mine')) {
        jump('/' + redirectUrl, 'switchTab')
      } else {
        if (redirectUrl.startsWith('passport/login/login')) {
          jump('/pages/order/order', 'switchTab')
        } else {
          jump('/' + redirectUrl)
        }
      }
      store.commit('user/setHistory', '')
    } else {
      jump('/pages/order/order?login=1', 'switchTab')
    }
  }
}
